package cn.hxsteel.storage.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.hxsteel.storage.core.config.constant.CommonConst;

@Controller
public class ImageCodeController extends HttpServlet
{
    public ImageCodeController()
    {
	super();
    }
    
    public void destroy()
    {
	super.destroy();
    }
    
    public void init()
	    throws ServletException
    {
	super.init();
    }
    
    @RequestMapping( "/out/imageCode" )
    public void service( HttpServletRequest request, HttpServletResponse response )
	    throws ServletException, IOException
    {
	// 禁止缓存
	response.setHeader( "Pragma", "No-cache" );
	response.setHeader( "Cache-Control", "No-cache" );
	response.setDateHeader( "Expires", 0 );
	// 指定生成的响应是图片
	response.setContentType( "image/jpeg" );
	// 生成图片外框
	int width = 68;
	int height = 22;
	BufferedImage image = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB ); // 创建BufferedImage类的对象
	Graphics g = image.getGraphics(); // 创建Graphics类的对象
	g.setColor( Color.WHITE ); // 设置背景颜色
	g.fillRect( 0, 0, width, height ); // 绘制一个填色矩形
	g.setColor( Color.LIGHT_GRAY ); // 设置边框颜色
	g.drawRect( 0, 0, width - 1, height - 1 );
	g.setColor( Color.BLACK ); // 设置前景颜色
	// 画一条线
	for (int i = 10; i < 12; i++)
        {
            int x1 = 1;
            int y1 = i;
            int x2 = 66;
            int y2 = i;
            g.drawLine( x1, y1, x2, y2 );
        }
	// 生成5个随机字母
	Random random = new Random();
	Font font = new Font( "Arial", Font.BOLD, 13 );
	g.setFont( font );
	String codeView = "";
	String[] letterArray = getLetterArray();
	for ( int i = 0; i < 5; i++ )
	{
	   String codeItem = letterArray[random.nextInt(letterArray.length)];
	   codeView += codeItem;
	   g.drawString(codeItem, (i == 0 ? 2 : 14 * i), 16);
	}
	// 将生成的验证码保存到Session中
	HttpSession session = request.getSession( true );
	session.setAttribute( CommonConst.SESSION_CODE_CONTEXT, codeView );
	g.dispose();
	ImageIO.write( image, "JPEG", response.getOutputStream() );
    }
    
    /**
     * 18个大写字母（注：排除ABEFGHPR）
     * 
     * @return
     */
    private String[] getLetterArray()
    {
	return new String[] { "C", "D", "I", "J", "K", "L", "M", "N", "O", "Q", "S", "T", "U", "V", "W", "X", "Y", "Z" };
    }
}
